package com.tegtech.tools.wechat.util;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate请求工具类
 * @Author Jun
 * @date 2020年5月31日 下午1:56:28
 */
public class RestTemplateUtil {
	
	public static RestTemplate getInstance() {
    	RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        return restTemplate;
    }
	
	/**
	 *基于RestTemplate的请求
	 * @param url			请求地址
	 * @param httpMethod	请求方式	
	 * @param params		请求参数
	 * @param headers		请求头	
	 * @param clazz			结果转换对象类型
	 * @return
	 */
	@SuppressWarnings({ "rawtypes" })
	public static <T> T send(String url, HttpMethod httpMethod, Map<String, Object> params, MultiValueMap<String, Object> headers, Class<T> clazz) {
		try {
			HttpEntity requestEntity = buildHttpEntity(params, headers);
			// 进行网络请求,访问url接口
			ResponseEntity<T> responseEntity = getInstance().exchange(url, httpMethod, requestEntity, clazz);
			if (responseEntity != null && responseEntity.hasBody()) {
				return responseEntity.getBody();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 构建HttpEntity
	 * @param params	请求参数
	 * @param headers	请求头
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static HttpEntity buildHttpEntity(Map<String, Object> params, MultiValueMap<String, Object> headers) {
		if(params == null && headers == null) {
			return null;
		}
		if(params == null) {
			params = new LinkedHashMap<>();
		}
		if(headers == null) {
			headers = new LinkedMultiValueMap<>();
		}
		return new HttpEntity(params, headers);
	}
	
}
